package org.zjvis.datascience.common.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.db.meta.Column;
import cn.hutool.db.meta.Table;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.zjvis.datascience.common.constant.DatasetConstant;
import org.zjvis.datascience.common.dto.dataset.DatasetColumnDTO;
import org.zjvis.datascience.common.dto.dataset.DatasetJsonInfo;
import org.zjvis.datascience.common.model.ColumnSchema;
import org.zjvis.datascience.common.model.TableSchema;
import org.zjvis.datascience.common.util.db.JDBCUtil;

import java.nio.charset.StandardCharsets;
import java.sql.Types;
import java.util.*;

/**
 * @description sql相关
 * @date 2020-07-01
 */
public class SqlUtil {

    /**
     * 格式化字段名（添加 `）
     *
     * @param colName
     * @return
     */
    public static String formatColName(String colName) {
        if (StringUtils.isBlank(colName)) {
            return colName;
        }
        if (!colName.startsWith("`")) {
            colName = "`" + colName;
        }
        if (!colName.endsWith("`")) {
            colName = colName + "`";
        }

        return colName;
    }

    /**
     * 防止字段和保留字段冲突
     *
     * @param colName
     * @return
     */
    public static String formatPGSqlColName(String colName) {
        if (StringUtils.isBlank(colName)) {
            return colName;
        }
        if (!colName.startsWith("\"")) {
            colName = "\"" + colName;
        }
        if (!colName.endsWith("\"")) {
            colName = colName + "\"";
        }

        return colName;
    }

    /**
     * 格式化值（添加 '）
     * @param value
     * @return
     */
    public static String formatValue(String value) {
        if (StringUtils.isBlank(value)) {
            return value;
        }
        if (!value.startsWith("'")) {
            value = "'" + value;
        }
        if (!value.endsWith("'")) {
            value = value + "'";
        }

        return value;
    }

    public static List<String> formatPGSqlCols(Iterable<String> iterable) {
        Iterator<String> iterator = iterable.iterator();
        List<String> ret = Lists.newArrayList();
        while (iterator.hasNext()) {
            ret.add("\"" + iterator.next().replaceAll("\"", "\"\"") + "\"");
        }
        return ret;
    }

    /**
     * 按本系统规则重新规范字段名
     *
     * @param fieldName
     * @return
     */
    public static String formatFieldName(String fieldName) {
        return fieldName.toLowerCase().trim().replaceAll("\\s+", StrUtil.UNDERLINE)
            .replaceAll("\\p{Punct}", StrUtil.UNDERLINE)
            .replaceAll("\uFEFF", "");
    }

    /**
     * 按本系统规则重新规范字段名
     *
     * @param fieldName
     * @return
     */
    public static String formatFieldNameWithSpace(String fieldName) {
        return fieldName.toLowerCase().trim().replaceAll("\\p{Space}", "");
    }

    public static String cutStr(String strs, int length) {
        int sum = 0;
        String finalStr = "";
        if (null == strs || strs.getBytes(StandardCharsets.UTF_8).length <= length) {
            finalStr = (strs == null ? "" : strs);
        } else {
            for (int i = 0; i < strs.length(); i++) {
                String str = strs.substring(i, i + 1);
                // 累加单个字符字节数
                sum += str.getBytes(StandardCharsets.UTF_8).length;
                if (sum > length) {
                    finalStr = strs.substring(0, i);
                    break;
                }
            }
        }
        return finalStr;
    }

    /**
     * 生成insert语句
     *
     * @param ts
     * @return
     */
    public static String generateInsertSql(TableSchema ts, String type) {
        StringBuilder sb = new StringBuilder();
        StringBuilder col = new StringBuilder();
        StringBuilder value = new StringBuilder();

        String table = ts.getTableName();

        List<ColumnSchema> columns = ts.getColumns();
        if (columns.isEmpty()) {
            return null;
        }

        if ("mysql".equalsIgnoreCase(type)) {
            table = formatColName(table);
        }

        sb.append("insert into " + table + " ");
        col.append("(");
        value.append("(");
        for (ColumnSchema cs : columns) {
            String colName = cs.getColumnName();
            if ("mysql".equalsIgnoreCase(type)) {
                colName = formatColName(colName);
            } else if ("pgsql".equalsIgnoreCase(type)) {
                colName = formatPGSqlColName(colName);
            }
            col.append(colName + ",");
            value.append("?,");
        }
        /*去掉末尾的逗号*/
        String colStr = col.substring(0, col.length() - 1) + ")";
        String valueStr = value.substring(0, value.length() - 1) + ");";

        return sb + colStr + " values " + valueStr;
    }

//    /**
//     *
//     * @param ts
//     * @param sourceTargetType
//     * @return
//     */
//    public static String generateCreateTableSql(TableSchema ts, String sourceTargetType) {
//        if ("mysql-pgsql".equalsIgnoreCase(sourceTargetType)) {
//            return generateCreateTableSqlMysqlToPGSql(ts);
//        } else {
//            return generateCreateTableSqlMysqlToMysql(ts);
//        }
//    }

    /**
     * 生成建表语句(MySql - MySql版)
     *
     * @param ts
     * @return
     */
    public static String generateCreateTableSql(TableSchema ts) {
        StringBuffer sb = new StringBuffer();
        String table = ts.getTableName();
        sb.append("CREATE TABLE " + formatColName(table) + " (");
        List<ColumnSchema> columns = ts.getColumns();
        if (columns.isEmpty()) {
            return null;
        }
        for (ColumnSchema cs : columns) {
            String colName = cs.getColumnName();
            String colType = cs.getColumnType() == null ? "VARCHAR" : cs.getColumnType();
            Integer colSize = cs.getColumnSize() == null ? 1 : cs.getColumnSize();

            switch (colType) {
                case "DATETIME":
                case "DOUBLE":
                case "FLOAT":
                case "JSON":
                case "TEXT":
                    sb.append("\r\n")
                        .append(formatColName(colName))
                        .append(" ")
                        .append(colType)
                        .append(" DEFAULT NULL,");
                    break;
                case "LONGTEXT":
                case "BLOB":
                    sb.append("\r\n")
                        .append(formatColName(colName))
                        .append(" ").append(colType)
                        .append(",");
                    break;
                case "DECIMAL":
                    if (cs.getIntegerDigits() != null && cs.getDecimalPlaces() != null) {
                        sb.append("\r\n")
                            .append(formatColName(colName))
                            .append(" ")
                            .append(colType)
                            .append("(")
                            .append(cs.getIntegerDigits() + cs.getDecimalPlaces())
                            .append(",")
                            .append(cs.getDecimalPlaces())
                            .append(") DEFAULT NULL,");
                    } else {
                        sb.append("\r\n")
                            .append(formatColName(colName))
                            .append(" ")
                            .append(colType)
                            .append(" DEFAULT NULL,");
                    }
                    break;
                case "TIMESTAMP":
                    sb.append("\r\n")
                        .append(formatColName(colName))
                        .append(" ")
                        .append(colType)
                        .append(" NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,");
                    break;
                default:
                    sb.append("\r\n")
                        .append(formatColName(colName))
                        .append(" ")
                        .append(colType)
                        .append("(")
                        .append(colSize)
                        .append(") DEFAULT NULL,");
                    break;
            }
        }
        /* 去掉末尾的逗号 */
        String res = sb.substring(0, sb.length() - 1) + " )";

        return res;
    }

    /**
     * 生成建表语句(MySql - MySql版)
     *
     * @param ts
     * @return
     */
    public static String generateCreateTableSqlMysqlToMysql(TableSchema ts) {
        StringBuffer sb = new StringBuffer();
        String table = ts.getTableName();
        sb.append("CREATE TABLE " + formatColName(table) + " (");
        List<ColumnSchema> columns = ts.getColumns();
        if (columns.isEmpty()) {
            return null;
        }
        for (ColumnSchema cs : columns) {
            String colName = cs.getColumnName();
            String colType = cs.getColumnType() == null ? "VARCHAR" : cs.getColumnType();
            Integer colSize = cs.getColumnSize() == null ? 1 : cs.getColumnSize();

            switch (colType) {
                case "DATETIME":
                case "DOUBLE":
                case "FLOAT":
                case "JSON":
                case "TEXT":
                    sb.append("\r\n")
                        .append(formatColName(colName))
                        .append(" ")
                        .append(colType)
                        .append(" DEFAULT NULL,");
                    break;
                case "LONGTEXT":
                case "BLOB":
                    sb.append("\r\n")
                        .append(formatColName(colName))
                        .append(" ").append(colType)
                        .append(",");
                    break;
                case "DECIMAL":
                    if (cs.getIntegerDigits() != null && cs.getDecimalPlaces() != null) {
                        sb.append("\r\n")
                            .append(formatColName(colName))
                            .append(" ")
                            .append(colType)
                            .append("(")
                            .append(cs.getIntegerDigits() + cs.getDecimalPlaces())
                            .append(",")
                            .append(cs.getDecimalPlaces())
                            .append(") DEFAULT NULL,");
                    } else {
                        sb.append("\r\n")
                            .append(formatColName(colName))
                            .append(" ")
                            .append(colType)
                            .append(" DEFAULT NULL,");
                    }
                    break;
                case "TIMESTAMP":
                    sb.append("\r\n")
                        .append(formatColName(colName))
                        .append(" ")
                        .append(colType)
                        .append(" NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,");
                    break;
                default:
                    sb.append("\r\n")
                        .append(formatColName(colName))
                        .append(" ")
                        .append(colType)
                        .append("(")
                        .append(colSize)
                        .append(") DEFAULT NULL,");
                    break;
            }
        }
        /* 去掉末尾的逗号 */
        String res = sb.substring(0, sb.length() - 1) + " )";

        return res;
    }

    public static Integer encodeType(String colType) {
        switch (StringUtils.upperCase(colType)) {
            case "INT":
            case "INT2":
            case "INT4":
            case "INT8":
            case "INTEGER":
            case "TINYINT":
            case "SMALLINT":
                return Types.INTEGER;
            case "BIGINT":
                return Types.BIGINT;
            case "REAL":
            case "NUMERIC":
            case "FLOAT4":
            case "DECIMAL":
            case "FLOAT":
            case "DOUBLE":
            case "DOUBLE PRECISION":
                return Types.NUMERIC;
            case "DATE":
            case "TIME":
            case "YEAR":
            case "DATETIME":
            case "TIMESTAMP":
                return Types.DATE;
            case "JSON":
                return Types.OTHER;
            case "ARRAY":
                return Types.ARRAY;
            default:
                //CHARACTER VARYING
                return Types.CHAR;
        }
    }

    public static String encodeTypeName(Integer type) {
        switch (type) {
            case Types.INTEGER:
                return "INTEGER";
            case Types.BIGINT:
                return "BIGINT";
            case Types.NUMERIC:
                return "DECIMAL";
            case Types.DATE:
                return "DATE";
            case Types.OTHER:
                return "JSON";
            case Types.ARRAY:
                return "ARRAY";
            default:
                return "CHARACTER VARYING";
        }
    }

    /**
     * @param ts
     * @return
     */
    public static String generateCreateTableSqlForGP(Table ts) {
        StringBuffer sb = new StringBuffer();

        String table = ts.getTableName();
        sb.append("CREATE TABLE " + JDBCUtil.GP_WRAPPER.wrap(table) + " (");
        Collection<Column> columns = ts.getColumns();
        if (columns.isEmpty()) {
            return null;
        }
        for (Column cs : columns) {
            String colName = JDBCUtil.GP_WRAPPER.wrap(SqlUtil.formatFieldName(cs.getName()));
            String colType = cs.getTypeName() == null ? "VARCHAR" : cs.getTypeName();
            Integer colSize = cs.getSize();

            switch (colType) {
                case "INT2":
                case "INT4":
                case "INT8":
                case "TEXT":
                case "DATE":
                case "TIME":
                case "TIMESTAMP":
                    sb.append("\r\n")
                        .append(colName)
                        .append(" ")
                        .append(colType)
                        .append(" DEFAULT NULL,");
                    break;
                case "YEAR":
//               TODO 待测试     cs.setTypeName("INT2");
                    sb.append("\r\n")
                        .append(colName)
                        .append(" ")
                        .append("INT2")
                        .append(" DEFAULT NULL,");
                    break;
                case "BINARY":
                case "VARBINARY":
                case "TINYBLOB":
                case "BLOB":
                case "MEDIUMBLOB":
                case "LONGBLOB":
                case "BYTEA":
                    sb.append("\r\n")
                        .append(colName)
                        .append(" ")
                        .append("BYTEA")
                        .append(" DEFAULT NULL,");
                    break;
                case "GEOMETRY":
                case "ENUM":
                case "SET":
                    sb.append("\r\n")
                        .append(colName)
                        .append(" ")
                        .append("VARCHAR")
                        .append(" DEFAULT NULL,");
                    break;
                case "NUMERIC":
                    if (cs.getDecimalDigits() > 0) {
                        sb.append("\r\n")
                            .append(colName)
                            .append(" ")
                            .append(colType)
                            .append("(")
                            .append(cs.getSize())
                            .append(",")
                            .append(cs.getDecimalDigits())
                            .append(") DEFAULT NULL,");
                    } else {
                        sb.append("\r\n")
                            .append(colName)
                            .append(" ")
                            .append(colType)
                            .append(" DEFAULT NULL,");
                    }
                    break;
                case "BIT":
                    // bit时，最小取8位
                    if (colSize > 1) {
                        colSize = Math.max(colSize, 8);
                    }
                case "ROWID":
                    //数据实际长度比metadata获取的长度长，所以直接长度加一倍（暂定）
                    colSize *= 2;
                    colType = "VARCHAR";
                default:
                    if (colSize < 1) {
                        colSize = 1;
                    }
                    sb.append("\r\n")
                        .append(colName)
                        .append(" ")
                        .append(colType)
                        .append("(")
                        .append(colSize)
                        .append(") DEFAULT NULL,");
                    break;
            }
        }
        /* 去掉末尾的逗号 */
        String res = sb.append(JDBCUtil.GP_WRAPPER.wrap(DatasetConstant.DEFAULT_ID_FIELD))
            .append(" serial PRIMARY KEY )").toString();

        return res;
    }

    /**
     * @param ts
     * @return
     */
    public static TableSchema changeMysqlSchemaToPGSql(TableSchema ts) {
        List<ColumnSchema> newColumns = new ArrayList<>();
        List<ColumnSchema> columns = ts.getColumns();
        if (columns.isEmpty()) {
            return null;
        }
        for (ColumnSchema cs : columns) {
            String colType = cs.getColumnType() == null ? "VARCHAR" : cs.getColumnType();

            switch (colType) {
                case "FLOAT":
                case "DOUBLE":
                case "DECIMAL":
                case "NUMERIC":
                    cs.setColumnType("NUMERIC");
                    break;
                case "JSON":
                case "TEXT":
                case "LONGTEXT":
                case "TINYTEXT":
                case "MEDIUMTEXT":
                    cs.setColumnType("TEXT");
                    break;
                case "DATETIME":
                case "TIMESTAMP":
                    cs.setColumnType("TIMESTAMP");
                    break;
                case "VARCHAR":
                    // oracle类型
                case "VARCHAR2":
                    cs.setColumnType("VARCHAR");
                    break;
                case "TINYINT":
                case "TINYINT UNSIGNED":
                case "SMALLINT":
                case "SMALLINT UNSIGNED":
                    cs.setColumnType("INT2");
                    break;
                case "YEAR":
                    cs.setColumnType("YEAR");
                    break;
                case "INT":
                case "INT UNSIGNED":
                case "MEDIUMINT":
                case "MEDIUMINT UNSIGNED":
                    cs.setColumnType("INT4");
                    break;
                case "BIGINT":
                case "BIGINT UNSIGNED":
                    cs.setColumnType("INT8");
                    break;
                default:
                    break;
            }
            newColumns.add(cs);
        }
        ts.setColumns(newColumns);

        return ts;
    }

    /**
     * 转换后只能用column的typeName
     *
     * @param t
     * @return
     */
    public static Table changeMysqlSchemaToPGSql(Table t) {
        Collection<Column> columns = t.getColumns();
        if (columns.isEmpty()) {
            return null;
        }
        Table newTable = Table.create(t.getTableName());

        for (Column cs : columns) {
            String colType = cs.getTypeName() == null ? "VARCHAR" : cs.getTypeName();

            switch (colType) {
                case "FLOAT":
                case "DOUBLE":
                case "DECIMAL":
                case "NUMERIC":
                    cs.setTypeName("NUMERIC");
                    break;
                case "JSON":
                case "TEXT":
                case "LONGTEXT":
                case "TINYTEXT":
                case "MEDIUMTEXT":
                    cs.setTypeName("TEXT");
                    break;
                case "DATETIME":
                case "TIMESTAMP":
                    cs.setTypeName("TIMESTAMP");
                    break;
                case "VARCHAR":
                    // oracle类型
                case "VARCHAR2":
                    cs.setTypeName("VARCHAR");
                    break;
                case "TINYINT":
                case "TINYINT UNSIGNED":
                case "SMALLINT":
                case "SMALLINT UNSIGNED":
                    cs.setTypeName("INT2");
                    break;
                case "YEAR":
                    cs.setTypeName("YEAR");
                    break;
                case "INT":
                case "INT UNSIGNED":
                case "MEDIUMINT":
                case "MEDIUMINT UNSIGNED":
                    cs.setTypeName("INT4");
                    break;
                case "BIGINT":
                case "BIGINT UNSIGNED":
                    cs.setTypeName("INT8");
                    break;
                default:
                    break;
            }
            newTable.setColumn(cs);
        }

        return newTable;
    }

    /**
     * 转换默认数据库字段类型返回给前端（包括：Mysql,greenplum）
     *
     * @param colType
     * @return
     */
    public static String changeType(String colType) {
        return changeType(null, StringUtils.upperCase(colType));
    }

    /**
     * 转换字段类型返回给前端
     *
     * @param databaseType
     * @param colType
     * @return
     */
    public static String changeType(String databaseType, String colType) {
        switch (databaseType == null ? "" : databaseType.toLowerCase()) {
            case "oracle":
                return changeOracleColumnType(colType);
            default:
                return changeCommonDBColumnType(colType);
        }
    }

    /**
     * 转换默认数据库字段类型返回给前端（包括：Mysql,greenplum）
     *
     * @param column
     * @return
     */
    public static String changeType(Column column) {
        return changeType(null, column);
    }

    /**
     * 转换字段类型返回给前端
     *
     * @param dbType
     * @param column
     * @return
     */
    public static String changeType(String dbType, Column column) {
        switch (dbType == null ? "" : dbType.toLowerCase()) {
            case "oracle":
                return changeOracleColumnType(column.getTypeName());
            default:
                return changeCommonDBColumnType(column.getTypeEnum().name());
        }
    }

    /**
     * 转换通用数据库字段类型返回给前端（包括：Mysql,greenplum） int  #数字 , varchar #字符串, decimal #小数, date #日期,text #文本
     *
     * @param colType
     * @return
     */
    public static String changeCommonDBColumnType(String colType) {
        /* 去除UNSIGNED与SIGNED */
        colType = colType.replace("UNSIGNED", "").trim();
        colType = colType.replace("SIGNED", "").trim();
        // 更改这里的时候 记得同时更改 SqlUtil.encodeType 保持一致
        switch (colType) {
            case "INT":
            case "INT2":
            case "INT4":
            case "INT8":
            case "INTEGER":
            case "TINYINT":
            case "SMALLINT":
            case "BIGINT":
                return "int";
            case "REAL":
            case "FLOAT4":
            case "NUMERIC":
            case "DECIMAL":
            case "FLOAT":
            case "DOUBLE":
            case "DOUBLE PRECISION":
                return "decimal";
            case "DATE":
            case "TIME":
            case "YEAR":
            case "DATETIME":
            case "TIMESTAMP":
                return "date";
            default:
                return "varchar";
//            case "TEXT":
//            case "LONGTEXT":
//            case "TINYTEXT":
//            case "MEDIUMTEXT":
//                return "text";
        }
    }

    /**
     * 转换Oracle字段类型返回给前端 int  #数字 , varchar #字符串, decimal #小数, date #日期,text #文本
     *
     * @param colType
     * @return
     */
    public static String changeOracleColumnType(String colType) {

        /**
         * 通过hutool获取到的Oracle字段类型
         *
         * NUMBER,VARCHAR2,NVARCHAR2,CHAR,NCHAR,ROWID
         * CLOB,NCLOB,BLOB,LONG,LONG ROW,BFILE
         * FLOAT,BINARY_FLOAT,BINARY_DOUBLE
         * INTERVAL DAY(2) TO SECOND(6),INTERVAL YEAR(2) TO MONTH
         * DATE,TIMESTAMP(6)，TIMESTAMP(6) WITH TIME ZONE,TIMESTAMP(6) WITH LOCAL TIME ZONE
         */
        switch (colType) {
            case "INT":
            case "INTEGER":
            case "SMALLINT":
            case "BIGINT":
                return "int";
//            case "BLOB":
//            case "CLOB":
//            case "LONG":
//            case "LONG ROW":
//            case "BFILE":
//            case "NCLOB":
//                return "text";
            case "DOUBLE":
            case "BINARY_DOUBLE":
            case "FLOAT":
            case "BINARY_FLOAT":
            case "NUMBER":
                return "decimal";
            default:
                if (StringUtils.containsAny(colType, "TIMESTAMP", "DATE")) {
                    return "date";
                }
                return "varchar";
        }
    }

    public static Table changeOracleSchemaToPGSql(Table t) {
        Collection<Column> columns = t.getColumns();
        if (columns.isEmpty()) {
            return null;
        }
        Table newTable = Table.create(t.getTableName());

        for (Column cs : columns) {
            String colType = cs.getTypeName() == null ? "VARCHAR" : cs.getTypeName();
            /**
             * 通过hutool获取到的Oracle字段类型
             *
             * NUMBER,VARCHAR2,NVARCHAR2,CHAR,NCHAR,ROWID
             * CLOB,NCLOB,BLOB,LONG,LONG ROW,BFILE
             * FLOAT,BINARY_FLOAT,BINARY_DOUBLE
             * INTERVAL DAY(2) TO SECOND(6),INTERVAL YEAR(2) TO MONTH
             * DATE,TIMESTAMP(6)，TIMESTAMP(6) WITH TIME ZONE,TIMESTAMP(6) WITH LOCAL TIME ZONE
             */
            switch (colType) {
                case "FLOAT":
                case "DOUBLE":
                case "DECIMAL":
                case "NUMERIC":
                case "NUMBER":
                    cs.setTypeName("NUMERIC");
                    break;
                case "TEXT":
                case "CLOB":
                case "NCLOB":
                case "LONG":
                    cs.setTypeName("TEXT");
                    break;
                case "BLOB":
                case "RAW":
                case "LONG RAW":
                case "BFILE":
                    cs.setTypeName("BYTEA");
                    break;
                case "DATE":
                    cs.setTypeName("DATE");
                    break;
                case "ROWID":
                    cs.setTypeName("ROWID");
                    break;
                default:
                    if (StringUtils.contains(colType, "TIMESTAMP")) {
                        cs.setTypeName("TIMESTAMP");
                    } else {
                        cs.setTypeName("VARCHAR");
                    }
                    break;
            }
            newTable.setColumn(cs);
        }

        return newTable;
    }

    /**
     * 是否整数
     *
     * @param type database column type
     * @return
     */
    public static boolean isInteger(int type) {
        return type == Types.SMALLINT || type == Types.INTEGER || type == Types.BIGINT;
    }

    /**
     * 是否浮点数
     *
     * @param type database column type
     * @return
     */
    public static boolean isDecimal(int type) {
        return type == Types.FLOAT || type == Types.DOUBLE || type == Types.DECIMAL
            || type == Types.NUMERIC;
    }

    /**
     * 是否数字
     *
     * @param type database column type
     *             5, 4,-5,6,8, 3, 2
     * @return
     */
    public static boolean isNumeric(int type) {
        return type == Types.SMALLINT || type == Types.INTEGER || type == Types.BIGINT
            || type == Types.FLOAT || type == Types.DOUBLE || type == Types.DECIMAL
            || type == Types.NUMERIC;
    }

    /**
     * 是否日期类型
     *
     * @param type database column type
     * @return
     */
    public static boolean isDate(int type) {
        return type == Types.DATE || type == Types.TIME || type == Types.TIME_WITH_TIMEZONE
            || type == Types.TIMESTAMP || type == Types.TIMESTAMP_WITH_TIMEZONE;
    }

    /**
     * 是否字符串类型
     *
     * @param type database column type
     *             -1, 12, 1
     * @return
     */
    public static boolean isString(int type) {
        return type == Types.LONGVARCHAR || type == Types.VARCHAR || type == Types.CHAR;
    }

    public static Object genDefaultValue(int type){
        if (isString(type)){
            return "null";
        }else if (isInteger(type)){
            return 0;
        }else if (isDecimal(type)){
            return 0.0f;
        }else if(isDate(type)){
            return new Date().getTime();
        }else {
            return "unknown";
        }
    }

    /**
     * 不需要导入字段移除、脱敏类型转换等特殊处理
     *
     * @param tableMeta
     * @param dj
     * @return
     */
    public static Table columnSpecialProcess(Table tableMeta, DatasetJsonInfo dj) {
        Collection<Column> columns = tableMeta.getColumns();
        if (columns.isEmpty()) {
            return tableMeta;
        }
        Map<String, String> map = new HashMap<>();
        for (DatasetColumnDTO columnMessage : dj.getColumnMessage()) {
            if (columnMessage.getImportColumn()) {
                map.put(columnMessage.getName().toLowerCase(), columnMessage.getDataMaskingType());
            }
        }

        Table newTable = Table.create(tableMeta.getTableName());

        for (Column cs : columns) {
            if (map.containsKey(cs.getName().toLowerCase())) {
                if (StringUtils.isNotBlank(map.get(cs.getName().toLowerCase()))) {
                    switch (map.get(cs.getName().toLowerCase())) {
                        case "md5":
                        case "sha1":
                        case "mosaic":
                            cs.setSize(50);
                            cs.setTypeName("VARCHAR");
                        default:
                            break;
                    }
                }
                newTable.setColumn(cs);
            }
        }

        return newTable;
    }

}
